package com.uphone.kingmall.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.blankj.utilcode.util.LogUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.china.zhuoyue.R;
import com.uphone.kingmall.adapter.PoiSearchAdapter;
import com.uphone.kingmall.bean.LocationAddressInfo;
import com.uphone.kingmall.utils.ConstansUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @ Create_time: 2018/9/7 on 11:31.
 * @ description：
 * @ author: vchao  blog: http://blog.csdn.net/zheng_weichao
 */
public class PoiSearchActivity extends Activity implements PoiSearch.OnPoiSearchListener {

    private PoiResult poiResult;
    private PoiSearchAdapter poiSearchAdapter;
    private ArrayList<LocationAddressInfo> dataList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.kingmall_popup_rv);
        // 设置状态栏底色颜色
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        RecyclerView rvPoi = findViewById(R.id.rv);
        rvPoi.setLayoutManager(new LinearLayoutManager(this));
        poiSearchAdapter = new PoiSearchAdapter();
        rvPoi.setAdapter(poiSearchAdapter);
        initListener();
        search();
    }

    private void initListener() {

        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        poiSearchAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent().putExtra(ConstansUtils.BEAN, dataList.get(position));
                setResult(10, intent);
                finish();
            }
        });
    }

    private void search() {
        EditText searchKey = findViewById(R.id.searchkey);
        searchKey.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                LogUtils.e("s:" + s.toString());
                doSearchQuery(s.toString());
            }
        });
    }

    private int currentPage;
    private PoiSearch.Query query;
    private PoiSearch poiSearch;

    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery(String key) {
        LogUtils.e("key");
        currentPage = 0;
        //不输入城市名称有些地方搜索不到
        // 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query = new PoiSearch.Query(key, "", "");
        // 设置每页最多返回多少条poiitem
        query.setPageSize(10);
        // 设置查询页码
        query.setPageNum(currentPage);

        //构造 PoiSearch 对象，并设置监听
        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        //调用 PoiSearch 的 searchPOIAsyn() 方法发送请求。
        poiSearch.searchPOIAsyn();
    }

    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        LogUtils.e("onPoiSearched");
        LogUtils.e("rCode:" + rCode);
        //rCode 为1000 时成功,其他为失败
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            // 解析result   获取搜索poi的结果
            LogUtils.e("result:" + result);
            if (result != null && result.getQuery() != null) {
                LogUtils.e("query:" + query);
                if (result.getQuery().equals(query)) {  // 是否是同一条
                    LogUtils.e("result:" + result);
                    poiResult = result;
                    //自己创建的数据集合
                    if (dataList == null) {
                        dataList = new ArrayList<LocationAddressInfo>();
                    }
                    dataList.clear();
                    // 取得第一页的poiitem数据，页数从数字0开始
                    //poiResult.getPois()可以获取到PoiItem列表
                    List<PoiItem> poiItems = poiResult.getPois();

                    //若当前城市查询不到所需POI信息，可以通过result.getSearchSuggestionCitys()获取当前Poi搜索的建议城市
                    List<SuggestionCity> suggestionCities = poiResult.getSearchSuggestionCitys();
                    //如果搜索关键字明显为误输入，则可通过result.getSearchSuggestionKeywords()方法得到搜索关键词建议。
                    List<String> suggestionKeywords = poiResult.getSearchSuggestionKeywords();

                    LogUtils.e("poiItems:" + poiItems.size());
                    //解析获取到的PoiItem列表
                    for (PoiItem item : poiItems) {
                        //获取经纬度对象
                        LatLonPoint llp = item.getLatLonPoint();
                        double lon = llp.getLongitude();
                        double lat = llp.getLatitude();
                        //返回POI的名称
                        String title = item.getTitle();
                        //返回POI的地址
                        String text = item.getSnippet();
                        dataList.add(new LocationAddressInfo(lon, lat, title, text));
                        LogUtils.e("poi返回数据：", String.valueOf(lon), String.valueOf(lat), title, text);
                    }
                    LogUtils.e("dataList.size():" + dataList.size());
                    poiSearchAdapter.setNewData(dataList);
                }
            } else {
                Toast.makeText(PoiSearchActivity.this, "无搜索结果", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(PoiSearchActivity.this, "错误码" + rCode, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }
}